package com.wmwj.hxlj.service.impl;

import com.wmwj.hxlj.entity.Article;
import com.wmwj.hxlj.entity.ArticleLike;
import com.wmwj.hxlj.entity.Tag;
import com.wmwj.hxlj.entity.User;
import com.wmwj.hxlj.entity.vo.ArticleVo;
import com.wmwj.hxlj.entity.vo.PageResult;
import com.wmwj.hxlj.entity.vo.UserVo;
import com.wmwj.hxlj.mapper.ArticleLikeMapper;
import com.wmwj.hxlj.mapper.ArticleMapper;
import com.wmwj.hxlj.mapper.UserMapper;
import com.wmwj.hxlj.service.ArticleService;
import com.wmwj.hxlj.service.TagService;
import com.wmwj.hxlj.utils.BeanCopyUtils;
import com.wmwj.hxlj.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UserMapper UserMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleLikeMapper articleLikeMapper;


    @Override
    public Result<List<Article>> getDraftArticles() {
        List<Article> drafts = articleMapper.findByStatus(0); // 0表示草稿状态
        if (drafts == null || drafts.isEmpty()) {
            return Result.error("没有草稿文章");
        }
        return Result.success(drafts);
    }

    @Override
    @Transactional//确保数据库操作成功，回滚事务
    public Result publishArticle(Article article) {
        //检查作者是否存在
        User author = UserMapper.findById(article.getAuthorId());
        if (author == null) {
            throw new RuntimeException("作者不存在");
        }

        // 设置创建时间、更新时间、状态
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        //状态
        article.setStatus(article.getStatus());


        //根据标签id设置标签
        String[] tags = article.getTag().split(",");
        String strTag = "";
        for (int i = 0; i < tags.length; i++) {
            int id = Integer.parseInt(tags[i]);
            strTag += tagService.findByid(id);
            // 如果不是最后一个元素，添加逗号
            if (i < tags.length - 1) {
                strTag += ",";
            }
        }
        article.setTag(strTag);

        int row = articleMapper.insert(article);
        if (row == 0) {
            return Result.error("发布失败");
        }

        // 增加标签使用次数
        if (tags.length > 0) {
            tagService.batchIncrementTagUseCount(tags);
        }

        ArticleVo articleVo = BeanCopyUtils.copyBean(article, ArticleVo.class);

        return Result.success(articleVo);
    }

    @Override
    @Transactional
    public Result<String> deleteArticle(Long id) {
        // 获取文章信息
        Article article = articleMapper.findById(id);
        if (article == null) {
            return Result.error("文章不存在");
        }

        Date updateTime = new Date();

        // 删除文章
        int row = articleMapper.deleteById(id,updateTime);
        if (row == 0) {
            return Result.error("删除失败");
        }

        // 减少标签使用次数
        String[] tags = article.getTag().split(",");
        if (tags.length > 0) {
            tagService.batchDecrementTagUseCount(tags);
        }

        return Result.success("删除成功");
    }

    @Override
    @Transactional
    public Result updateArticle(Article article) {
        // 获取文章信息
        Article existingArticle = articleMapper.findById(article.getId());
        if (existingArticle == null) {
            return Result.error("文章不存在");
        }

        if(article.getAuthorId() != existingArticle.getAuthorId())
            return Result.error("文章作者不匹配");



        article.setUpdateTime(new Date());

        int row = articleMapper.update(article);
        if (row == 0) {
            return Result.error("更新失败");
        }

        // 更新标签使用次数
        String[] tags = article.getTag().split(",");
        if (tags.length > 0) {
            tagService.batchIncrementTagUseCount(tags);
        }

        ArticleVo articleVo = BeanCopyUtils.copyBean(articleMapper.findById(article.getId()), ArticleVo.class);

        return Result.success(articleVo);
    }

    @Override
    public Result getArticleById(Long id) {
        Article article = articleMapper.findById(id);
        if (article == null) {
            return Result.error("文章不存在");
        }
        ArticleVo articleVo = BeanCopyUtils.copyBean(article, ArticleVo.class);
        return Result.success(articleVo);
    }

    @Override
    public Result<List<ArticleVo>> getAllArticles(Integer pageStarts) {

        int pageStart = (pageStarts - 1) * 10;
        int pageSize = 10;

        List<Article> articles = articleMapper.selectAllArticles(pageStart, pageSize);
        if (articles == null || articles.isEmpty()) {
            return Result.error("没有文章了");
        }
        List<ArticleVo> articleVo = BeanCopyUtils.copyBeanList(articles, ArticleVo.class);
        return Result.success(articleVo);
    }

    @Override
    public Result<List<ArticleVo>> getUserDraftArticles(Long id) {
        List<Article> drafts = articleMapper.findDraftArticlesByUserId(id);
        if (drafts == null || drafts.isEmpty()) {
            return Result.error("没有草稿");
        }

        List<ArticleVo> draftsVo = BeanCopyUtils.copyBeanList(drafts, ArticleVo.class);

        return Result.success(draftsVo);
    }

    @Override
    public Result<List<ArticleVo>> searchArticles(String keyword, Integer pageStarts) {
        if (keyword == null || keyword.isEmpty()) {
            return Result.error("关键字不能为空");
        }
        int pageStart = (pageStarts - 1) * 10;
        int pageSize = 10;

        List<Article> articles = articleMapper.searchByKeyword(keyword, pageStart, pageSize);
        if (articles == null || articles.isEmpty()) {
            return Result.error("没有找到相关文章");
        }

        List<ArticleVo> articleVo = BeanCopyUtils.copyBeanList(articles, ArticleVo.class);
        return Result.success(articleVo);
    }

    @Override
    public Result<List<ArticleVo>> getUserArticles(Long id, Integer pageStarts) {
        int pageStart = (pageStarts - 1) * 10;
        int pageSize = 10;
        List<Article> article = articleMapper.findByAuthorId(id, pageStart, pageSize);
        if (article == null || article.isEmpty()) {
            return Result.error("没有文章");
        }
        List<ArticleVo> articleVo = BeanCopyUtils.copyBeanList(article, ArticleVo.class);
        return Result.success("已获取到文章",articleVo);
    }

    @Override
    public Result<Integer> likeArticle(Long articleId, Long userId) {
        if (articleId == null) {
            throw new RuntimeException("文章不存在");
        }

        try {
            // 获取点赞状态，并检查是否为null
            ArticleLike likeStatus = articleLikeMapper.findLikeStatus(articleId, userId);
            if (likeStatus == null) {
                // 如果likeStatus为null，表示用户尚未点赞，执行点赞操作
               int row = articleMapper.likeArticle(articleId);
               int row2 = articleLikeMapper.insertLikeStatus(articleId, userId);
                return Result.success("点赞成功",row2);
            } else if (!likeStatus.getIsDeleted()) {
                // 如果likeStatus为true，表示用户已经点赞，执行取消点赞操作
               int row =  articleMapper.unlikeArticle(articleId);
               int row2 = articleLikeMapper.deleteLikeStatus(articleId, userId);
                System.out.println("减");
                return Result.success("取消点赞成功",-row2);
            } else {
                // 如果likeStatus为false，表示用户尚未点赞，执行点赞操作
               int row = articleMapper.likeArticle(articleId);
                int row2 = articleLikeMapper.insertLikeStatus2(articleId, userId);
                System.out.println("增");
                return Result.success("点赞成功",row2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("点赞失败");
        }
    }

    @Override
    public Result<List<ArticleVo>> searchArticlesByTag(String tagName) {
        if (tagName == null || tagName.isEmpty())
            throw new RuntimeException("服务错误");

        List<Article> article = articleMapper.findByTag(tagName);
        if (article == null || article.isEmpty())
            throw new RuntimeException("没有找到相关文章");

        List<ArticleVo> articleVo = BeanCopyUtils.copyBeanList(article, ArticleVo.class);
        return Result.success("已获取到文章",articleVo);
    }

    @Override
    public Result<List<ArticleVo>> searchArticlesByCategoryId(Long categoryId, Integer pageStarts) {
        if (categoryId == null)
            throw new RuntimeException("服务错误");

        int pageStart = (pageStarts - 1) * 10;

        List<Article> article = articleMapper.findByCategoryId(categoryId, pageStart);
        if (article == null || article.isEmpty())
            throw new RuntimeException("没有找到相关文章");

        List<ArticleVo> articleVo = BeanCopyUtils.copyBeanList(article, ArticleVo.class);
        return Result.success("已获取到文章",articleVo);
    }

    @Override
    public Result<PageResult<Article>> adminGetAllArticles(Integer pageStarts) {
        int pageStart = (pageStarts - 1) * 10;
        int pageSize = 10;

        List<Article> articles = articleMapper.selectAllArticles(pageStart, pageSize);
        if (articles == null || articles.isEmpty()) {
            return Result.error("没有文章了");
        }
        PageResult<Article> pageResult = new PageResult<>(articles, articleMapper.countAllArticles());
        return Result.success(pageResult);
    }

    @Override
    public Result<PageResult<Article>> adminSearchArticles(String keyword, Integer pageStarts) {
        if (keyword == null || keyword.isEmpty()) {
            return Result.error("关键字不能为空");
        }
        int pageStart = (pageStarts - 1) * 10;
        int pageSize = 10;

        List<Article> articles = articleMapper.adminSearchByKeyword(keyword, pageStart, pageSize);
        if (articles == null || articles.isEmpty()) {
            return Result.error("没有找到相关文章");
        }
        PageResult<Article> pageResult = new PageResult<>(articles, articleMapper.adminCountByKeyword(keyword));
        return Result.success(pageResult);
    }

    @Override
    public Result<String> updateStatus(Long id) {
        if (id == null) {
            throw new RuntimeException("服务错误");
        }

        Article article = articleMapper.findById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在");
        }

        Date updateTime = new Date();
        articleMapper.updateStatus(id, 1, updateTime);
        return Result.success("操作成功");
    }

}